from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
from django.utils.html import strip_tags
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.forms import extras
from django.utils.translation import ugettext, ugettext_lazy as _


from planner.models import Trip
from planner.models import POI
from planner.models import Vote
from planner.models import TripUser

#def register(request):
#    if request.method == 'POST':
#        form = UserCreationForm(request.POST)
#        if form.is_valid():
#            new_user = form.save()
#            return HttpResponseRedirect('/trips/')
#    else:
#        form = UserCreationForm()
#    return render(request, "register.html", {'form': form,})

class TripUserRegistrationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and
    password.
    """
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }
    username = forms.RegexField(label=_("Username"), max_length=30,
        regex=r'^[\w.@+-]+$',
        help_text = _("Required. 30 characters or fewer. Letters, digits and "
                      "@/./+/-/_ only."),
        error_messages = {
            'invalid': _("This value may contain only letters, numbers and "
                         "@/./+/-/_ characters.")})
    password1 = forms.CharField(label=_("Password"),
        widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text = _("Enter the same password as above, for verification."))

    class Meta:
        model = TripUser
        fields = ( 'username',)
        exclude = ('is_staff', 'is_active', 'date_joined', 'last_login', 'first_name', 'last_name','twitter_id','access_token','access_token_secret','twitter_username', 'email')

    def clean_username(self):
        # Since User.username is unique, this check is redundant,
        # but it sets a nicer error message than the ORM. See #13147.
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1", "")
        password2 = self.cleaned_data["password2"]
        if password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'])
        return password2

    def save(self, commit=True):
        user = super(TripUserRegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class TripForm(forms.ModelForm):
    start_date = forms.DateField(widget=extras.SelectDateWidget)
    end_date   = forms.DateField(widget=extras.SelectDateWidget)

    class Meta:
        model = Trip
        fields = ['trip_name', 'start_date', 'end_date', 'participants', 'owner']
        exclude = ('owner', )


class PoiForm(forms.ModelForm):
    description = forms.CharField(required=True, widget=forms.widgets.Textarea(attrs={'class': 'descform'}))
    class Meta:
        model = POI
        fields = ['poi_name', 'location','description', 'is_definitive']
        exclude = ('part_of_trip', 'image_file_name',)

class VoteForm(forms.Form):
    pid      = forms.CharField(max_length=100, widget=forms.HiddenInput, required=True)
    voted    = forms.BooleanField(required=False)

    def clean(self):
        cleaned_data = super(VoteForm, self).clean()
        pid = cleaned_data.get("pid")
        voted = cleaned_data.get("voted")
        if not POI.objects.filter(id=pid).exists():
            raise forms.ValidationError("Oops... it seems like you're voting for a place of interest that doesn't exist!")
        return cleaned_data
